package cn.devcat.sso.service.impl;

import cn.devcat.sso.entity.DevcatTask;
import cn.devcat.sso.entity.PageData;
import cn.devcat.sso.entity.SearchCommonParam;
import cn.devcat.sso.mapper.DevcatTaskMapper;
import cn.devcat.sso.service.IDevcatTaskService;
import cn.devcat.sso.util.PageHelperUtil;
import cn.devcat.sso.util.UserUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DevcatTaskServiceImpl extends ServiceImpl<DevcatTaskMapper, DevcatTask> implements IDevcatTaskService {

  @Autowired
  UserUtil userUtil;

  @Resource
  DevcatTaskMapper taskMapper;
  @Override
  public void addTask(DevcatTask task) {
    task.setCreateTime(LocalDateTime.now());
    String userId = userUtil.getUserByRequest().getId();
    task.setUserId(userId);
    save(task);
  }

  @Override
  public void delTask(List<Long> ids) {
    removeBatchByIds(ids);
  }

  @Override
  public void delTaskByProjectIds(List<Long> ids) {
    remove(new QueryWrapper<DevcatTask>().in("project_id", ids));
  }

  @Override
  public void setTask(DevcatTask task) {
    updateById(task);
  }

  @Override
  public PageData<DevcatTask> getTaskList(SearchCommonParam param) {
    String userId = userUtil.getUserByRequest().getId();
    PageHelperUtil.handle(param);
    param.setUserId(userId);
    List<DevcatTask> taskList = taskMapper.getTaskList(param);
    return PageHelperUtil.makePageData(new PageInfo<>(taskList));
  }

  @Override
  public Map<String, Long> statistics() {
    String userId = userUtil.getUserByRequest().getId();
    long no_started_count = count(new QueryWrapper<DevcatTask>().eq("user_id", userId).eq("task_status", "no_started"));
    long started_count = count(new QueryWrapper<DevcatTask>().eq("user_id", userId).eq("task_status", "started"));
    long complete_count = count(new QueryWrapper<DevcatTask>().eq("user_id", userId).eq("task_status", "complete"));

    Map<String, Long> result = new HashMap<>();
    result.put("no_started", no_started_count);
    result.put("started", started_count);
    result.put("complete", complete_count);
    return result;
  }
}
